<?php
namespace Api\Controller;

use Api\Controller;

//http://localhost/WaiterServer/?a=register

/**
 * Class IndexController
 * @package Home\Controller
 *
 * 注册/登录业务
 */
class IndexController extends AppController
{
    /**
     * 注册
     */
    public function register()
    {
        if (IS_POST) {
            $account = I('post.account');
            $password = I('post.password');
            $client_type = I('post.client_type');
            $appid = I('post.appid');
        } elseif (IS_GET) {
            $account = I('get.account');
            $password = I('get.password');
            $appid = I('get.appid');
            $client_type = I('get.client_type');
        }

        if (empty($account) || empty($password)) {
            $this->apiReturn(400, '账号或密码不能为空', NULL, ApiReturn);
            return;
        }

        if ($this->isExist($account)) {
            $this->apiReturn(401, '已注册', null, ApiReturn);
            return;
        }

        $password = md5($account . $password);

        $nonce = $this->createNoncestr(32);
        $currentTime = time();
        $tmpArr = array($nonce, $appid, $password, $account, $client_type, $currentTime);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $token = md5($tmpStr);

        $data = array(
            'account' => $account,
            'password' => $password,
            'user_token' => $token,
            'expire_time' => UserTokenExpireTime,
            'client_type' => $client_type,
            'create_time' => $currentTime
        );

        $result = D('user')->add($data);

        if ($result) {
            $data = array(
                'account' => $account,
                'uid' => $result,
                'user_token' => $token,
                'expire_time' => UserTokenExpireTime,
                'registerTime' => $currentTime
            );
            $this->apiReturn(200, '注册成功', $data, ApiReturn);
        } else {
            $this->apiReturn(401, '注册失败', null, ApiReturn);
        }
    }

    /**
     *  登录
     */
    public function login()
    {
        if (IS_POST) {
            $account = I('post.account');
            $password = I('post.password');
            $client_type = I('post.client_type');
            $appid = I('post.appid');
        } elseif (IS_GET) {
            $account = I('get.account');
            $password = I('get.password');
            $appid = I('get.appid');
            $client_type = I('get.client_type');
        }

        if (empty($account) || empty($password)) {
            $this->apiReturn(400, '账号和密码不能为空', NULL, ApiReturn);
            return;
        }

        $password = md5($account . $password);

        /*检查是否存在此账户*/
        $device = D('user');
        $condition['account'] = $account;
        $condition['password'] = $password;
        $condition['client_type'] = $client_type;
        $resultFind = $device->where($condition)->find();
        if (!$resultFind) {
            $this->apiReturn(400, '账号或密码错误', null, ApiReturn);
            return;
        }

        /*如果存在则生成新的token*/
        $nonce = $this->createNoncestr(32);
        $currentTime = time();
        $tmpArr = array($nonce, $appid, $password, $account, $client_type, $currentTime);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $token = md5($tmpStr);

        /*更新新的token*/
        $updataData['user_id'] = $resultFind['user_id'];
        $updataData['user_token'] = $token;
        $updataData['expire_time'] = UserTokenExpireTime;
        $updataData['update_time'] = $currentTime;
        $result = D('user')->save($updataData);

        /*通知客户端更新*/
        if ($result) {
            $data = array(
                'account' => $account,
                'uid' => $resultFind['user_id'],
                'user_token' => $token,
                'expire_time' => UserTokenExpireTime,
                'registerTime' => $currentTime
            );
            $this->apiReturn(200, '登录成功', $data, ApiReturn);
        } else {
            $this->apiReturn(401, '登录失败', null, ApiReturn);
        }
    }


    public function test(){

        $data['test1'] = "test one";
        $data['test2'] = "test two";

        $this->apiReturn(200, 'test', $data, ApiReturn);
    }

    /*************************以下为基础函数*************************************/

    /**
     * 判断设备是否存在
     * @param $deviceid
     * 设备ID
     * @return bool
     */
    private function isExist($account)
    {
        $device = D('user');
        $condition['account'] = $account;
        $resultFind = $device->where($condition)->find();
        return $resultFind != NULL;
    }


    /**
     * 作用：产生随机字符串，不长于32位
     * @param int $length
     * @return string
     */
    function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}